package com.xia.juan.work.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import com.xia.juan.work.domain.DataCompareVO;
import com.xia.juan.work.enums.FileTypeEnum;
import com.xia.juan.work.service.DataCompareService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author wang
 */
@Slf4j
@RestController
@RequestMapping("/data-compare")
public class DataCompareController {

    private final DataCompareService dataCompareService;

    public DataCompareController(DataCompareService dataCompareService) {
        this.dataCompareService = dataCompareService;
    }

    @PostMapping("/upload-file")
    public void uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("fileType") FileTypeEnum fileTypeEnum) {
        log.info("接收到上传文件的请求, fileName=[{}]", file.getOriginalFilename());
        String extName = FileUtil.extName(file.getOriginalFilename());
        Assert.notNull(extName, "文件类型不能为空");
        if (fileTypeEnum == FileTypeEnum.EXCEL && !fileTypeEnum.getType().contains(extName.toLowerCase())) {
            throw new RuntimeException("Excel文件格式错误");
        }
        if (fileTypeEnum == FileTypeEnum.TXT && !fileTypeEnum.getType().contains(extName.toLowerCase())) {
            throw new RuntimeException("TXT文件格式错误");
        }
        try {
            dataCompareService.uploadFile(file, fileTypeEnum);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new RuntimeException(Objects.isNull(e.getMessage()) ? "上传文件失败" : e.getMessage());
        }
        log.info("上传文件完成");
    }

    @PostMapping("/score-review")
    public List<String> scoreReview(@RequestBody DataCompareVO dataCompareVO) throws IOException {
        log.info("接收到成绩复核请求");
        try {
            List<String> errorInfo = dataCompareService.scoreReview(dataCompareVO.getFieldMappingEntityList(),
                    dataCompareVO.getSheetName());
            log.info("成绩复核完成");
            return errorInfo;
        } catch (Exception e) {
            log.error("成绩复核失败", e);
            throw e;
        }
    }

    @DeleteMapping("/delete-file")
    public void deleteFile(@RequestParam("fileName") String fileName) {
        log.info("开始删除文件");
        try {
            dataCompareService.deleteFile(fileName);
        } catch (IOException e) {
            log.error("文件删除失败", e);
            throw new RuntimeException("文件删除失败");
        }
        log.info("文件已删除");
    }
}
